package be.xios.projectquiz.player;

import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.swing.JOptionPane;

import be.xios.projectquiz.game.Game;
import be.xios.projectquiz.game.Player;
import be.xios.projectquiz.global.CardsViewer;
import be.xios.projectquiz.global.SharedItems;
import be.xios.projectquiz.global.StreamMethods;
import be.xios.projectquiz.profiles.Gamer;

/// <summary>
/// Deze klasse verzorgt de communicatie tussen player en server!
/// </summary>
/// <author>Sebastian Kubski</author>
public class PlayerClient implements Runnable {

	private String ip;
	private SharedItems shared;
	private Gamer gamer = new Gamer();
	private Game currentGame;
	private Socket socket;
	private CardsViewer viewer;
	private StreamMethods streamMethods;
	private Player currPlayer;
	private Date date;
	private ExecutorService executor;

	// CONSTRUCTOR
	public PlayerClient(String ip, SharedItems shared, CardsViewer viewer) {
		this.ip = ip;
		this.shared = shared;
		this.viewer = viewer;
		this.date = new Date();
	}

	// BEGIN RUN
	@Override
	public void run() {
		// PlayerClient info op boot
		String logString = "[" + new Timestamp(date.getTime())
				+ "] CLIENTSIDE: " + Thread.currentThread().getName();
		System.out.println(logString + " is " + gamer.getName());
		try {

			socket = new Socket(ip, 5000);
			streamMethods = new StreamMethods(socket);
			shared.veranderConnectStatus("Connected with the server");
			shared.enableConnect(false);

			streamMethods.openObjectOutputStream();

			streamMethods.getObjectOutput().writeObject(gamer);
			System.out.println(logString +" "+ gamer.getName() + " heeft zijn profiel verzonden");
			viewer.next();

		}
		catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch(ConnectException ex){
        	JOptionPane.showMessageDialog(null,"Kan niet verbinden met de server. \t | \t Cannot connect with the server. \t","Waarschuwing | Warning",JOptionPane.ERROR_MESSAGE);
		}
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		while (shared.getGame() == null) {
			try {
				Thread.sleep(2000);
				System.out.println(logString + " " + gamer+ " no game received so far");
				streamMethods.openObjectInputStream();

				currentGame = (Game) streamMethods.getObjectInput()
						.readObject();
				System.out.println(logString + " " + gamer + " has received "
						+ currentGame);
				shared.setGame(currentGame, gamer.getName());
				viewer.show("LOGIN");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch(NullPointerException ex){
				// Do nothing, wacht totdat de speler connect
			}
		}
		// Controle
		while (shared.getPlayer() == null) {
			try {
				Thread.sleep(2000);
				System.out.println(logString + gamer
						+ " didn't create a player(group)");

				if (shared.getPlayer() != null) {
					currPlayer = shared.getPlayer();

					System.out.println(logString + " is " + currPlayer);

					streamMethods.openObjectOutputStream();
					streamMethods.getObjectOutput().writeObject(currPlayer);
					System.out.println(logString + gamer
							+ " has succesfully sent " + currPlayer);

					viewer.show("WAITFORSTART");
					currentGame = null;
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		while (currentGame == null) {
			System.out.println(logString + gamer
					+ " is waiting for an updated game");
			try {
				streamMethods.openObjectInputStream();
				currentGame = (Game) streamMethods.getObjectInput()
						.readObject();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (currentGame != null) {
				executor = Executors.newCachedThreadPool();
				// origineel frame met de keuzes en login invisible maken
				shared.houdiniOriginalFrame(false);

				System.out.println(logString + " opende de GAMEPLAYERGUI");
				
				if (currentGame.getGameName().equals("BLOKKEN")) {
					PlayerClientBlokken pBlokken = new PlayerClientBlokken(streamMethods, currentGame, currPlayer);
					executor.execute(pBlokken);
				} else 
				if (currentGame.getGameName().equals("ZAALQUIZ")) {
					PlayerClientZaalQuiz pZaalQuiz = new PlayerClientZaalQuiz(streamMethods, currentGame, currPlayer);
					executor.execute(pZaalQuiz);
				}
			}
		}
	}// EINDE RUN
}
